//
//  ClientTool.m
//  Demo
//
//  Created by 龚碧容 on 2017/9/15.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "ClientTool.h"
#import "AppDelegate.h"

#import "sys/utsname.h"
#import <UIDevice+FCUUID.h>

#define kWaitTime 30.0f

@implementation ClientTool

+(void)alertLoginWithVC{

    AppDelegate *appD = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UINavigationController *nav = (UINavigationController *)appD.tabbarController.selectedViewController;
    
    QLMLoginViewController *loginController = [QLMLoginViewController new];
    loginController.resultBlock=^(BOOL success){};
    QLMCustomNavCtr *nav12=[[QLMCustomNavCtr alloc] initWithRootViewController:loginController];

    [nav presentViewController:nav12 animated:YES completion:nil];
}


//AFNetWorking存在内存泄露，需要对AFHTTPSessionManager进行单例封
+(AFHTTPSessionManager *)sharedManager{
    
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        manager = [AFHTTPSessionManager manager];
        manager.operationQueue.maxConcurrentOperationCount = 5;//最大请求并发任务数
        manager.requestSerializer.timeoutInterval=kWaitTime;//最大等待时间
        
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.requestSerializer= [AFJSONRequestSerializer serializer];
        
        manager.responseSerializer.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml",@"text/json",@"text/html",@"application/json",@"text/plain",nil];
        
        [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];//设置请求头
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        
        [manager.requestSerializer setValue:@"text/html;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        
    });
    return manager;
}

+ (void)postUrlPath:(NSString *)urlPath withParamers:(NSMutableDictionary *)tokenDic type:(NSMutableArray *)headerImageArray success:(void (^)(id responseObject))success failure:(void (^)( NSError *error))failure{
    
    NSString *tokenStr=[NSString stringWithFormat:@"bearer%@",tokenDic[@"token"]];
    [[self sharedManager].requestSerializer setValue:tokenStr forHTTPHeaderField:@"Authorization"];
    
    [[self sharedManager] POST:urlPath parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //上传图片
        for (int i = 0; i < headerImageArray.count; i ++) {
            UIImage *image = headerImageArray[i];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.28);
            [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"upload%d",i+1] fileName:@".png" mimeType:@"png"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}


+ (void)postUrlPathAndFormData:(NSString *)urlPath withParamers:(NSMutableDictionary *)parameters andBody:(NSDictionary *)body success:(void (^)(id responseObject))success failure:(void (^)( NSError *error))failure{
    
    NSString *resultStr = [NSString stringWithFormat:@"%@%@",kBaseURL,urlPath];
    NSString *POST_BOUNDS=@"test";
    NSURL *url = [NSURL URLWithString:resultStr];
    NSMutableString *bodyContent = [NSMutableString string];
    
    for(NSString *key in parameters.allKeys){
        id value = [parameters objectForKey:key];
        [bodyContent appendFormat:@"--%@\r\n",POST_BOUNDS];
        [bodyContent appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
        [bodyContent appendFormat:@"%@\r\n",value];
    }
    
    [bodyContent appendFormat:@"--%@--\r\n",POST_BOUNDS];
    
    NSData *bodyData=[bodyContent dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request  = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
    
    [request addValue:[NSString stringWithFormat:@"multipart/form-data;boundary=%@",POST_BOUNDS] forHTTPHeaderField:@"Content-Type"];
    
    if ([body allKeys].count!=0) {
        NSString *tokenStr=[NSString stringWithFormat:@"bearer %@",body[@"token"]];
        [request addValue:tokenStr forHTTPHeaderField:@"Authorization"];
    }else{
        [request addValue:@"" forHTTPHeaderField:@"Authorization"];
    }
    
    [request addValue: [NSString stringWithFormat:@"%zd",bodyData.length] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:bodyData];
    __autoreleasing NSError *error=nil;
    __autoreleasing NSURLResponse *response=nil;
    
//    if (IOS9_OR_LATER) {
//
//        NSURLSession *session = [NSURLSession sharedSession];
//        NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//
//            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
//            NSLog(@"从服务器获取到数据 %@",dict);
//            success(dict);
//        }];
//        //5.最后一步，执行任务，(resume也是继续执行)。
//        [sessionDataTask resume];
//
//    }else{
    
        NSData *reciveData= [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        if(error){
            NSLog(@"出现异常%@",error);
        }else{
            NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)response;
            if(httpResponse.statusCode==200){
                success([self dictionaryWithJsonString:[[NSString alloc]initWithData:reciveData encoding:NSUTF8StringEncoding]]);
            }else{
                NSLog(@"服务器返回失败>>%@",[[NSString alloc]initWithData:reciveData encoding:NSUTF8StringEncoding]);
            }
        }
    
//    }
    
    return;
}

+ (void)postUrlPath:(NSString *)urlPath withParamers:(NSMutableDictionary *)parameters andBody:(NSDictionary *)body success:(void (^)(id responseObject))success failure:(void (^)( NSError *error))failure{

    if ([body allKeys].count!=0) {
        NSString *tokenStr=[NSString stringWithFormat:@"bearer %@",body[@"token"]];
        [[self sharedManager].requestSerializer setValue:tokenStr forHTTPHeaderField:@"Authorization"];
       // [ClientTool pushToLoginVC]; //在此判断token是否过期 过期跳转到登录界面
    }else{
        [[self sharedManager].requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
    }
    
    NSString *osVersion=[NSString stringWithFormat:@"%@%@",[[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion]];
    NSString *app_version=[NSString stringWithFormat:@"%@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
    [[self sharedManager].requestSerializer setValue:@"iOS" forHTTPHeaderField:@"os"];//操作系统
    [[self sharedManager].requestSerializer setValue:osVersion forHTTPHeaderField:@"os_version"];//操作系统版本
    [[self sharedManager].requestSerializer setValue:@"xmkx" forHTTPHeaderField:@"client"];//app名
    [[self sharedManager].requestSerializer setValue:[[UIDevice currentDevice] uuid] forHTTPHeaderField:@"imei"];//标识
    [[self sharedManager].requestSerializer setValue:app_version forHTTPHeaderField:@"app_version"];//app版本号
    [[self sharedManager].requestSerializer setValue:@"iPhone" forHTTPHeaderField:@"phone_brand"];//手机品牌
    [[self sharedManager].requestSerializer setValue:[self iphoneType] forHTTPHeaderField:@"phone_model"];//手机型号
    [[self sharedManager].requestSerializer setValue:@"1.0" forHTTPHeaderField:@"client_version"];//接口版本号

    
    NSString *resultStr = [NSString_Parameters getResultURLWithPath:urlPath paramers:parameters andBody:body requestTYpe:@"post"];

//    NSString *resultStr = [NSString stringWithFormat:@"%@%@",kBaseURL,urlPath];
//    resultStr = [resultStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [[self sharedManager] POST:resultStr parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        //返回请求返回进度
//        NSLog(@"downloadProgress-->%@",downloadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        //请求成功返回数据
        if (responseObject != nil) {
            NSError *error;
            
            NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
            if (code == -1) {
                ETToast(responseObject[@"msg"]);
                [self alertLoginWithVC];
                return;
            }
            
            if (!error) {
                success(responseObject);
            }else{
                failure(error);
            }
            
            
        }else{
            NSError *error;
            failure(error);
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        NSLog(@"error-->%@",error);
        failure(error);
    }];
    
    return;
}

+ (void)getUrlPath:(NSString *)urlPath withParamers:(NSDictionary *)parameters  andBody:(NSDictionary *)body success:(void (^)(id responseObject))success failure:(void (^)( NSError *error))failure{
    
    if ([body allKeys].count!=0) {
        NSString *tokenStr=[NSString stringWithFormat:@"bearer %@",body[@"token"]];
        [[self sharedManager].requestSerializer setValue:tokenStr forHTTPHeaderField:@"Authorization"];
    }else{
        [[self sharedManager].requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
    }
    
    NSString *resultStr = [NSString_Parameters getResultURLWithPath:urlPath paramers:parameters andBody:body requestTYpe:@"get"];
    
    [[self sharedManager] GET:resultStr parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        //请求成功返回数据
        if (responseObject != nil) {
            NSError *error;
            if (!error) {
                success(responseObject);
            }else{
                failure(error);
            }
        }else{
            NSError *error;
            failure(error);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        NSLog(@"error-->%@",error);
        failure(error);
    }];
    return;
}

+ (void)uploadfileWithUrlPath:(NSString *)urlPath
                 withParamers:(NSDictionary *)parameters
                      andBody:(NSDictionary *)body
                     progress:(void (^)(NSProgress *uploadProgress))progress
                      success:(void (^)(id responseObject))success
                      failure:(void (^)( NSError *error))failure{
    
[[self sharedManager] POST:urlPath parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>_Nonnull formData) {
        success(formData);
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"uploadProgress-->%@",uploadProgress);
        progress(uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       failure(error);
    }];
}

+ (void)createUnloginedDownloadFileWithURLString:(NSString *)URLString
                            downloadFileProgress:(void(^)(NSProgress *downloadProgress))downloadFileProgress
                                   setupFilePath:(NSURL*(^)(NSURLResponse *response))setupFilePath
                       downloadCompletionHandler:(void (^)(NSURL *filePath, NSError *error))downloadCompletionHandler{
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:kWaitTime];
    NSLog(@"URLString  = %@",URLString);
    
    NSURLSessionDownloadTask *dataTask = [[self sharedManager] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        downloadFileProgress(downloadProgress);//下载进度
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return setupFilePath(response);//设置保存目录
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        downloadCompletionHandler(filePath,error);//下载完成
    }];
    
    [dataTask resume];
}

+ (NSString*)dictionaryToJson:(NSDictionary *)dic{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err){
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

//网络状态监听
+ (void)aFNetworkStatus{
    //创建网络监测者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //这里是监测到网络改变的block 可以写成switch方便
        //在里面可以随便写事件
        NSString *msg=nil;
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                msg=@"未知网络状态";
                break;
            case AFNetworkReachabilityStatusNotReachable:
                msg=@"无网络";
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                msg=@"蜂窝数据网";
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                msg=@"WiFi网络";
                break;
                
            default:
                break;
        }
        ETToast(msg);
    }];
    [manager startMonitoring];
}

+ (BOOL)isMobileValid:(NSString *)mobile{

    mobile=[mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length!= 11){
        return NO;
    }else{
        
        NSString *CM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        NSString *CU = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        NSString *CT = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

+ (BOOL)judgePassWordLegal:(NSString *)pass{
    BOOL result = false;
    if ([pass length] >= 6){
        //判断长度大于6位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,1000}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:pass];
    }
    return result;
}

+ (NSString *)md5:(NSString *)input{
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
}

+(BOOL)isNull:(id)object{
    // 判断是否为空串
    if ([object isEqual:[NSNull null]]) {
        return NO;
    }else if ([object isKindOfClass:[NSNull class]]){
        return NO;
    }else if (object==nil){
        return NO;
    }
    return YES;
}

+ (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

//+ (void)pushToLoginVC{
//    CATransition *anim = [[CATransition alloc] init];
//    anim.type = @"moveIn";
//    anim.duration = 0.5f;
//    anim.subtype = kCATransitionFromTop;
//    
//    QLMCustomWindow * window = [QLMCustomWindow sharedInstance];
//    window.resultblock=^(BOOL sucess){};
//    [window.layer addAnimation:anim forKey:nil];
//    window.windowLevel = normal;
//    window.hidden = NO;
//}

+ (NSString*)iphoneType{
    //需要导入头文件：#import <sys/utsname.h>
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    if([platform isEqualToString:@"iPhone4,1"])
        return @"iPhone 4S";
    if([platform isEqualToString:@"iPhone5,1"])
        return @"iPhone 5";
    if([platform isEqualToString:@"iPhone5,2"])
        return @"iPhone 5";
    if([platform isEqualToString:@"iPhone5,3"])
        return @"iPhone 5c";
    if([platform isEqualToString:@"iPhone5,4"])
        return @"iPhone 5c";
    if([platform isEqualToString:@"iPhone6,1"])
        return @"iPhone 5s";
    if([platform isEqualToString:@"iPhone6,2"])
        return @"iPhone 5s";
    if([platform isEqualToString:@"iPhone7,1"])
        return @"iPhone 6 Plus";
    if([platform isEqualToString:@"iPhone7,2"])
        return @"iPhone 6";
    if([platform isEqualToString:@"iPhone8,1"])
        return @"iPhone 6s";
    if([platform isEqualToString:@"iPhone8,2"])
        return @"iPhone 6s Plus";
    if([platform isEqualToString:@"iPhone8,4"])
        return @"iPhone SE";
    if([platform isEqualToString:@"iPhone9,1"])
        return @"iPhone 7";
    if([platform isEqualToString:@"iPhone9,2"])
        return @"iPhone 7 Plus";
    if([platform isEqualToString:@"iPhone10,1"])
        return @"iPhone 8";
    if([platform isEqualToString:@"iPhone10,4"])
        return @"iPhone 8";
    if([platform isEqualToString:@"iPhone10,2"])
        return @"iPhone 8 Plus";
    if([platform isEqualToString:@"iPhone10,5"])
        return @"iPhone 8 Plus";
    if([platform isEqualToString:@"iPhone10,3"])
        return @"iPhone X";
    if([platform isEqualToString:@"iPhone10,6"])
        return @"iPhone X";
    if([platform isEqualToString:@"i386"])
        return @"iPhone Simulator";
    if([platform isEqualToString:@"x86_64"])
        return @"iPhone Simulator";
    
    return platform;
}

@end
